import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../model/_models_chat.dart';
import '../model/_models_db.dart';
import '../utils/sputil.dart';
import 'contactprovider.dart';
import 'chatdetailprovider.dart';
import '../provider/websocketprovider.dart';


class ChatManagerProvider with ChangeNotifier {


  late ContactProvider addressBookProvider;

  ChatManagerProvider() {
    print("ChatManagerProvider");



    WebSocketProvider().onChat = (data) async {
      String sessionId = data["session_id"];

      if (providers.containsKey(sessionId)) {
        //providers[sessionId]?.receive(data);
      } else {
        /*
        var addressBook =
            await addressBookProvider.getAddressBook(context, data["from"]);

        startConversation(addressBook);

        providers[sessionId]?.receive(data);

         */
      }
    };

    WebSocketProvider().onPeers = (data) async{
      peers = data;

      checkToUserOnline();

      print("peers length:${peers.length}");

    };
  }



  List<Conversation> get conversations => _conversations;

  final List<Conversation> _conversations = <Conversation>[];
  ///peers
  ///id,name,user_agent
  List<dynamic> peers = <dynamic>[];

  int navigateIndex = 0;

  int chatIndex = -1;
  String chatSessionId = "";


  var spu = SpUtil();


  ///当前登录人用户名
  String get username {
    return spu.get<String>("username") as String;
  }
  
  /// 创建sesssionId
  String  newSessionId(String toUsername) {
    if (username.compareTo(toUsername) > 0) {
      return "${username},${toUsername}";
    } else {
      return "${toUsername},${username}";
    }
  }


  getCurrentConversation() {
    if (_conversations.isEmpty) {
      spu.setString("toUserId", "");

      return null;
    } else {
      var conversation = _conversations[chatIndex];

      spu.setString("toUserId", conversation.userId);

      return conversation;
    }
  }

  changeNavigate(int index) {
    navigateIndex = index;

    notifyListeners();
  }

  ///切换聊天
  changeChat(Conversation item) {

    chatIndex = _conversations.indexOf(item);
    chatSessionId = item.sessionId;

    notifyListeners();
  }

  ///启动聊天
  startConversation(ContactModel addressBook) {
    //第一选项卡是聊天界面
    navigateIndex = 0;
    Conversation item;

    if (_conversations.isEmpty ||
        _conversations
            .where((element) => element.userId == addressBook.Friendusername)
            .isEmpty) {
      item = Conversation(
          avatar: "images/avatar1.jpeg",
          title: addressBook.Friendname,
          des: "",
          updateAt: "",
          groupId: 0,
          userId: addressBook.Friendusername,
          type: 0,
          sessionId: newSessionId(addressBook.Friendusername)
      );
      _conversations.add(item);

      getChatDetailProvider(item.sessionId);

    } else {
      item = _conversations
          .where((element) => element.userId == addressBook.Friendusername)
          .first;
    }

    chatIndex = _conversations.indexOf(item);
    chatSessionId = item.sessionId;

    notifyListeners();

    return item;
  }


  static final providers = <String, ChangeNotifierProvider<ChatDetailProvider>>{};

  /// 为 聊天界面添加模型
  ChangeNotifierProvider<ChatDetailProvider> getChatDetailProvider(String sessionId){

    var items = _conversations.where((element) => element.sessionId == sessionId).toList();

    var conversation = items.first;

    if(!providers.containsKey(sessionId)) {
      providers[sessionId] = ChangeNotifierProvider((_) => ChatDetailProvider(conversation));
    }

    return providers[sessionId] as ChangeNotifierProvider<ChatDetailProvider>;
  }


  checkUserOnline(String username){

    bool toUserOnline = peers.where((element) => element["id"] == username).isNotEmpty;

    if(toUserOnline){
      print("${username} 上线");
    }else
    {
      print("${username} 离线");
    }

    return toUserOnline;
  }

  checkToUserOnline(){

    print("checkToUserOnline ${providers.length}");

    providers.forEach((key, value) {

      //value.checkUserOnline(peers);

    });
  }

}
